<template>
<!--header-->
  <div style="background-color:#fff;">
    <div class="header">
      <el-row style="background-color: white">
        <el-col :span="3">
          <el-image style="height: 100px;width: auto;margin-left: 10px;margin-top: -5px" @click="navigateToHome" src="image/login/DADARecipes.jpg"></el-image>
        </el-col>
        <el-col :span="12" :offset="20" style="margin-top: -85px;position: relative;">
          <!-- 显示用户的头像和用户名-->
          <el-image class="imgControl" :src="baseUrl+user.imgUrl"></el-image>
          <el-dropdown trigger="click">
            <span style="margin-left: 10px;margin-top:20px;font-size: 20px;font-weight: bold;">{{user.username}}<el-icon style="left: 5px;top: 3px"><ArrowDown /></el-icon></span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="navigateToUserMessage"><el-icon><User /></el-icon>个人中心</el-dropdown-item>
                <el-dropdown-item @click="logout"><el-icon><SwitchButton /></el-icon>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
      </el-row>
    </div>
  </div>
<!--收货地址表单-->
  <div style="display: flex; justify-content: center; margin-top: 120px;">
    <!-- 左侧 div -->
    <div style="flex: 1; background-color: lightgray; padding: 20px;background-image:url(/image/login/bread1.jpg);
     background-position: center top; background-repeat: no-repeat; background-size: cover;">
    </div>
   <!--新增收货地址按钮-->
    <el-card style="width: 1000px; height: auto; background-color: white;padding-left: 5px">
      <el-row>
        <el-col>
          <el-button type="warning" plain @click="addAddress">新增收货地址</el-button>
          <el-button type="warning" plain @click="navigateToCart">我的购物车>>></el-button>
        </el-col>
        <!--收货地址栏-->
        <el-col style="margin-top: 10px">
          <el-card style="width: 800px;height: auto;margin-bottom: 10px;" v-for="item in address">
            <el-row>
              <el-col>
                <span style="font-size: large">{{item.username}}</span>
                <el-icon style="font-size: large;padding-left: 7px;"><Edit /></el-icon>
                <el-icon style="font-size: large;padding-left: 630px" ><Close /></el-icon>
              </el-col>
              <el-col style="margin-top: 10px">
                <span style="font-size: small">收货人</span>
                <span style="padding-left: 25px;font-size: small">{{item.username}}</span>
              </el-col>
              <el-col>
                <span style="font-size: small">所在地区</span>
                <span style="padding-left: 10px;font-size: small">{{item.province+item.city+item.district}}</span>
              </el-col>
              <el-col>
                <span style="font-size: small">地址</span>
                <span style="padding-left: 35px;font-size: small">{{item.address}}</span>
              </el-col>
              <el-col>
                <span style="font-size: small">手机</span>
                <span style="padding-left: 35px;font-size: small">{{item.phone}}</span>
              </el-col>
            </el-row>
            <el-row>
              <el-col style="margin-top: 10px;margin-left: 600px">
                <!--点击按钮传输地址id-->
                <el-button link type="primary"  @click="delAddress(item.id)">删除</el-button>
                <el-button link type="primary" @click="changeAddress(item.id)">编辑</el-button>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
    <!-- 右侧 div -->
    <div style="flex: 1; background-color: lightgray; padding: 20px;background-image:url(/image/login/bread1.jpg);
     background-position: center top; background-repeat: no-repeat; background-size: cover;">
    </div>
  </div>
<!--新增收货地址弹窗-->
  <el-dialog v-model="dialogVisible">
    <span style="font-size: large;font-weight: bold">{{title}}</span>
    <el-form style="margin-top: 10px" label-position="top">
      <el-form-item label="收货人">
        <el-input placeholder="请输入收货人姓名" style="width: 45%" v-model="deliveryAddress.username"></el-input>
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input placeholder="请输入联系方式" style="width: 45%" v-model="deliveryAddress.phone"></el-input>
      </el-form-item>
      <el-form-item label="所在地区">
        <el-input placeholder="请输入省" style="width: 30%" v-model="deliveryAddress.province"></el-input>
        <el-input placeholder="请输入市" style="width: 30%;padding-left: 5px" v-model="deliveryAddress.city"></el-input>
        <el-input placeholder="请输入区" style="width: 30%;padding-left: 5px" v-model="deliveryAddress.district"></el-input>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input placeholder="请输入详细地址" style="width: 70%" v-model="deliveryAddress.address"></el-input>
      </el-form-item>
      <el-form-item style="padding-left: 500px">
        <el-button type="primary" plain @click="cancel">取消</el-button>
        <el-button type="primary" plain @click="saveAddresses">保存收货地址</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>


import {onMounted, ref} from "vue";
import router from "@/router";
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";

const baseUrl = getBaseUrl();
//定义title控制弹窗的标题
const title = ref("");

//使用localstorage获取当前用户登录的信息
const userData = getUser();
const userId = ref("")

//调用方法使用userId查询当前用户的信息
//定义变量用于存储当前用户的数据
const user = ref({
})

//通过userId向后端发送数据查询当前用户的信息
const queryMessage =()=>{
  userId.value=userData.id;
  axios.get(BASE_URL+'/v1/user/queryMessage/'+userId.value).then((response)=>{
    if(response.data.code===2000){
      //将数据赋值给userData
      user.value=response.data.data[0];
      //对gender进行判断
      if(user.value.gender === "1"){
        user.value.gender="女"
      }else if(user.value.gender === "0" ){
        user.value.gender="男"
      }
    }else{
      ElMessage.error("用户信息查询失败!");
    }
  })
}




//定义收货地址数组
const address = ref([
])
//定义变量用于控制弹窗是否显现
const dialogVisible = ref(false);

//定义方法用于跳转到个人用户页面
const navigateToUserMessage=()=>{
  router.push('/User')
}

//定义方法跳转到主页
const navigateToHome =()=>{
  router.push('/index')
}

//定义方法用于跳转到购物车页面
const navigateToCart =()=>{
  router.push('/cart');
}

//定义变量用于保存收货地址
const deliveryAddress = ref({
  userId:'',
  username:'',
  phone:'',
  province:'',
  city:'',
  district:'',
  address:'',
})

//定义方法用于新增收货地址
const addAddress =()=>{
  //将弹窗的抬头更新为新增收货地址
  title.value="新增收货地址";
   //展现弹窗
  dialogVisible.value=true;
}

//定义方法用于取消新增收货地址
const cancel =()=>{
  //提示用户是否确认取消
  if(confirm("确认取消新增地址吗?")){
    //清空表单的数据
    deliveryAddress.value={}
    //关闭弹窗
    dialogVisible.value=false;
  }
}

//定义方法向后端发送请求获取地址数据
const selectAddress =()=>{
  userId.value=userData.id;
  let data = qs.stringify({
    userId:userData.id
  })
  axios.get(BASE_URL+"/v1/user/selectAddress?"+data).then((response)=>{
    if(response.data.code===2000){
      //将返回的结果赋值到addressList
      address.value=response.data.data;
    }
  })
}
//挂载自动获取地址列表
onMounted(()=>{
  //查询用户信息
  queryMessage();
  //查询收货地址列表
  selectAddress();
})

//定义方法用于保存收货地址
const saveAddresses=()=>{
  //从localStorage中获取userId赋值给deliveryAddress
  deliveryAddress.value.userId=userId.value;
  let data = qs.stringify(deliveryAddress.value);
  //向后端发送新增地址请求
  axios.post(BASE_URL+"/v1/user/insertAddress/",data).then((response)=>{
    if(response.data.code===2000){
      //提示用户保存成功
      ElMessage.success("地址保存成功!")
      //清除deliveryAddress的数据
      deliveryAddress.value={};
      //关闭弹窗
      dialogVisible.value=false;
      //重新加载地址的卡片
      selectAddress();
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}

//定义方法用于编辑当前的地址(回显),此处id为当前地址的id
const changeAddress =(id)=>{
  //修改弹窗的抬头
  title.value="修改收货地址";
  //显示弹窗
  dialogVisible.value=true;
  userId.value=userData.id;
  //将数据转为字符串格式
  let data = qs.stringify({
    id:id,
    userId:userId.value}
  );
  //向后端发送请求查询对应id的地址数据
  axios.get(BASE_URL+"/v1/user/selectAddress?"+data).then((response)=>{
    if(response.data.code===2000){
      //将回显的数据赋值给deliveryAddress
      deliveryAddress.value=response.data.data[0];
    }else{
      ElMessage.error("数据查找失败!请稍后再试")
    }
  })

}
//定义方法用于删除当前地址,此处id为当前地址的id
const delAddress =(id)=>{
  //提示用户是否确认要删除地址
  if(confirm("确认要删除该地址吗?")){
    //向后端发送请求删除地址
    axios.post(BASE_URL+"/v1/user/deleteAddress/"+id).then((response)=>{
      if (response.data.code===2000){
        //提示用户地址删除成功
        ElMessage.success("地址删除成功!");
        //重新加载页面
        selectAddress();
      }else{
        ElMessage.error("删除失败!请稍后再试");
      }
    })
  }
}

//定义方法用于退出登录当前用户
const logout=()=>{
  //提示用户是否确认要退出登录
  if(confirm("确认要退出登录吗?")){
    //清空localStorage的用户信息
    localStorage.removeItem("user");
    //跳转到登录的页面
    router.push('/login');
  }
}

</script>



<style scoped>
/*定义header的样式*/
.header{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 200;
  background-color: white;
}
.imgControl{
  border: 1px solid white; /*设置边框*/
  border-radius: 50%; /*圆形*/
  width: 65px; /* 设置宽度 */
  height: 65px; /* 设置高度 */
  object-fit: cover; /* 确保图片填充整个容器 */
}

</style>